#include "logindialog.h"

#include "databasesutils.h"
#include <QGridLayout>
#include <QMessageBox>
#include <QSqlError>
#include <QSqlQuery>

LoginDialog::LoginDialog(QWidget *parent) : QDialog(parent) {
  userName = new QLabel(tr("用户名:"), this);
  passwd = new QLabel(tr("密码:"), this);

  userNameEdit = new QLineEdit(this);
  passwdEdit = new QLineEdit(this);
  passwdEdit->setEchoMode(QLineEdit::Password);

  userName->setBuddy(userNameEdit);
  passwd->setBuddy(passwdEdit);

  login = new QPushButton(tr("登录"), this);
  cancel = new QPushButton(tr("取消"), this);

  connect(login, &QPushButton::clicked, this, &LoginDialog::loginCheck);
  connect(cancel, &QPushButton::clicked,
          [this](bool checked) { this->close(); });

  QGridLayout *layout = new QGridLayout(this);
  layout->addWidget(userName, 0, 0, 1, 1);
  layout->addWidget(userNameEdit, 0, 1, 1, 2);
  layout->addWidget(passwd, 1, 0, 1, 1);
  layout->addWidget(passwdEdit, 1, 1, 1, 2);

  layout->addWidget(login, 2, 0, 1, 2);
  layout->addWidget(cancel, 2, 2, 1, 2);

  database = DataBasesUtils::getInstance();
  database.open();
  QSqlQuery query(database);
  QString check_table =
      "SELECT COUNT(*) FROM sqlite_master where type='table' and name='user'";
  query.prepare(check_table);
  if (!query.exec()) {
    qDebug() << query.lastError();
    return;
  } else {
    query.next();
    qDebug() << query.value(0).toString();
    if ("0" == query.value(0).toString()) {
      QString create_query = "CREATE TABLE user (id INTEGER PRIMARY KEY "
                             "AUTOINCREMENT ,username varchar(15),passwd "
                             "varchar(16))";
      query.prepare(create_query);
      query.exec();
      QString create_insert =
          "INSERT INTO user(username,passwd) values ('root','root')";
      query.prepare(create_insert);
      if (!query.exec()) {
        qDebug() << query.lastError();
      } else {
        qDebug() << "chenggong";
      }
    }
  }
  database.close();
}

LoginDialog::~LoginDialog() {}

void LoginDialog::loginCheck(bool checked) {
  Q_UNUSED(checked)
    database.open();
  QSqlQuery query(database);
  QString checkUser =
      "select username,passwd from user where username=:name	";
  query.prepare(checkUser);
  query.bindValue(":name", userNameEdit->text());
  if (!query.exec()) {
    qDebug() << query.lastError();
    return;
  } else {
    query.next();
    if (query.value(1).toString() == passwdEdit->text()) {
      done(QDialog::Accepted);
    } else {
      qDebug() << query.lastError();
      QMessageBox::warning(this, tr("账号或密码错误"), tr("请检查账号密码"));
    }
  }
}
